package com.union.sqlitedemo.mySqlite;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.union.sqlitedemo.bean.person;

import java.util.ArrayList;
import java.util.List;

/**
 * 操作数据工具类
 */
public class MyDebemanager {
    public MyDebemanager() {
    }

    //单例设计模式
    public static volatile MySqilteHelpter insatance = null;

    public static MySqilteHelpter getInstance(Context mContext) {
        if (insatance == null) {
            synchronized (MyDebemanager.class) {
                if (insatance == null) {
                    insatance = new MySqilteHelpter(mContext);
                }
            }
        }
        return insatance;
    }

    /**
     * sql 语句操作数据库
     *
     * @param db
     * @param sql
     */
    public static void sqlInsert(SQLiteDatabase db, String sql) {
        db.execSQL(sql);
    }


    /**
     * 通过sql语句查询数据
     *
     * @param db
     * @param sql
     * @param selectionArgs
     * @return
     */
    public static Cursor SelectDataBySql(SQLiteDatabase db, String sql, String[] selectionArgs) {
        Cursor cursor = null;
        if (db != null) {
            //selectionArgs sql语句中的占位符
            cursor = db.rawQuery(sql, null);
        }
        return cursor;
    }


    /**
     * 将cursor转化成list
     *
     * @param cursor
     * @return
     */
    public static ArrayList<person> CursortoList(Cursor cursor) {
        ArrayList<person> objects = new ArrayList<>();
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            person person = new person(id, name);
            objects.add(person);
        }
        return objects;
    }

    /**
     * 获得数据总条目
     *
     * @param db
     * @param tableName
     * @return
     */
    public static int getDataCount(SQLiteDatabase db, String tableName) {
        int count = 0;
        if (db != null) {
            String sql = "select * from " + tableName;
            Cursor cursor = db.rawQuery(sql, null);
            count = cursor.getCount();
        }
        return count;
    }

    /**
     * 分页操作
     * 每页的第一个下标为    （CurrentPage-1）*PageSize
     *
     * @param db
     * @param tableName
     * @param PageSize
     * @param CurrentPage
     * @return
     */
    public static List<person> getListByCurrentPager(SQLiteDatabase db, String tableName, int PageSize, int CurrentPage) {
        Cursor cursor = null;
        if (db != null) {
            int index = (CurrentPage - 1) * PageSize;
            String sql = "select * from " + tableName + " limit ?,?";
            cursor = db.rawQuery(sql, new String[]{index + "", PageSize + ""});
        }
        return CursortoList(cursor);
    }


}
